package org.folio.rest.impl.service;

import cn.hutool.core.util.StrUtil;
import io.vertx.core.AsyncResult;
import io.vertx.core.Context;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import org.folio.rest.jaxrs.model.Auxiliary;

import org.folio.rest.jaxrs.model.Party;
import org.folio.rest.persist.PgUtil;
import org.folio.rest.persist.PostgresClient;
import scala.Int;

import javax.xml.bind.ValidationException;
import java.util.Map;

public class AuxiliaryUpdateService  {
    private Map<String, String> okapiHeaders;
    private Context vertxContext;

    private final Logger logger = LoggerFactory.getLogger("modparty");

    public AuxiliaryUpdateService( Context vertxContext,Map<String, String> okapiHeaders){
        this.okapiHeaders = okapiHeaders;
        this.vertxContext = vertxContext;

    }

    private AuxiliaryUpdateService(){


    }

    public void updateAuxiliaryByParty(Party party, Boolean isAdd,Handler<AsyncResult<Auxiliary>> asyncResultHandler){
        Future<Auxiliary> future =Future.future();

           if (!StrUtil.isNullOrUndefined(party.getFacId()) && !StrUtil.isNullOrUndefined(party.getFacCount()) ){
               this.update(party.getFacId(),party.getFacName(),isAdd,Integer.parseInt(party.getFacCount()),future.completer());
           }
           if (!StrUtil.isNullOrUndefined(party.getVenueId()) && !StrUtil.isNullOrUndefined(party.getVenueCount()) ){
               this.update(party.getFacId(),party.getFacName(),isAdd,Integer.parseInt(party.getFacCount()),future.completer());
           }


        future.setHandler(reply->{
            if (reply.succeeded()){
                asyncResultHandler.handle(Future.succeededFuture(reply.result()));
            }else{
                asyncResultHandler.handle(Future.failedFuture(reply.cause()));
            }
        });
    }
    /**
     *
     * @param auxiliaryId 资源编号
     * @param auxiliaryName 资源名称
     * @param isAdd 是否添加
     * @param useAmount 变更的数量
     * @param asyncResultHandler
     */
    public void update(
                        String auxiliaryId,
                        String auxiliaryName,
                        Boolean isAdd,
                        Integer useAmount,
                        Handler<AsyncResult<Auxiliary>> asyncResultHandler){
        PostgresClient pg  = PgUtil.postgresClient(this.vertxContext,this.okapiHeaders);

        Future<Auxiliary> future =Future.future();
        if (StrUtil.isNullOrUndefined(auxiliaryId)){
            pg.closeClient(a->{});
            future.fail("资源编号不能为空");
            return;
        }
        if (StrUtil.isBlankOrUndefined(""+useAmount)){
            pg.closeClient(a->{});
            future.fail("资源使用数量不能为空");
            return;
        }
         pg.getById("auxiliary",auxiliaryId, Auxiliary.class, reply->{
            if (reply.succeeded()){
                Auxiliary auxiliary = reply.result();
                Integer amount = auxiliary.getAmount();
                Integer remainder = auxiliary.getRemainder();
                if (isAdd){
                    Integer result = useAmount + remainder;
                    if (result > amount){

                        auxiliary.setRemainder(amount);

                    }else if(result <= amount){
                        auxiliary.setRemainder(result);
                    }
                }else{
                    Integer result = remainder - useAmount;
                    if (result < 0){
                        pg.closeClient(a->{});
                        logger.info("资源变更，资源编号为【"+auxiliaryId+"】的数量不足");
                        future.fail("资源名称为【"+auxiliaryName+"】的数量不足，请更换或者更新资源数量再保存");
                        return;
                    }else if(result >= 0){
                        auxiliary.setRemainder(result);
                    }
                }
              pg.update("auxiliary",auxiliary,auxiliary.getId(),replyUpdate->{

                    if (replyUpdate.succeeded()){
                        if (replyUpdate.result().getUpdated() == 0){
                            pg.closeClient(a->{});
                            future.fail("资源名称为【"+auxiliaryName+"】更新失败，请更换或者更新资源数量再保存");
                            return;
                        }


                        future.completer();
                        pg.closeClient(a->{});

                    }else{
                        pg.closeClient(a->{});
                        logger.info("资源变更，资源编号为【"+auxiliary.getId()+"】更新失败");
                        future.fail("资源名称为【"+auxiliary.getName()+"】更新失败，请更换或者更新资源数量再保存");
                        return;
                    }
                });
            }else{
                pg.closeClient(a->{});
                logger.info("资源变更，找不到资源编号为【"+auxiliaryId+"】");
                future.fail("操作失败，找不到名称为【"+auxiliaryName+"】");
                return;
            }
        });

        future.setHandler(re->{
           if (re.succeeded()){
               asyncResultHandler.handle(Future.succeededFuture(re.result()));
           }else{
               asyncResultHandler.handle(Future.failedFuture(re.cause().getMessage()));
           }
        });
    }
    public void updateAuxiliary(
            String auxiliaryId,
            String auxiliaryName,
            Boolean isAdd,
            Integer useAmount,
            Handler<AsyncResult<Auxiliary>> asyncResultHandler) {
        PostgresClient pg = PgUtil.postgresClient(this.vertxContext, this.okapiHeaders);


        if (StrUtil.isNullOrUndefined(auxiliaryId)) {


            return;
        }
        if (StrUtil.isBlankOrUndefined("" + useAmount)) {


            return;
        }

        pg.getById("auxiliary",auxiliaryId,Auxiliary.class,reply->{
            if (reply.succeeded()){
                Auxiliary auxiliary = reply.result();
                Integer amount = auxiliary.getAmount();
                Integer remainder = auxiliary.getRemainder();
                if (isAdd){
                    Integer result = useAmount + remainder;
                    if (result > amount){

                        auxiliary.setRemainder(amount);

                    }else if(result <= amount){
                        auxiliary.setRemainder(result);
                    }
                }else{
                    Integer result = remainder - useAmount;
                    if (result < 0){
                        pg.closeClient(a->{});
                        logger.info("资源变更，资源编号为【"+auxiliaryId+"】的数量不足");

                        return;
                    }else if(result >= 0){
                        auxiliary.setRemainder(result);
                    }
                }
                pg.update("auxiliary",auxiliary,auxiliary.getId(),replyUpdate->{

                    if (replyUpdate.succeeded()){
                        if (replyUpdate.result().getUpdated() == 0){
                            return;
                        }
                        asyncResultHandler.handle(Future.succeededFuture(auxiliary));
                    }else{
                        asyncResultHandler.handle(Future.failedFuture("资源变更，资源编号为【"+auxiliary.getId()+"】更新失败"));
                        logger.info("资源变更，资源编号为【"+auxiliary.getId()+"】更新失败");
                        return;
                    }
                });

            } else{
            logger.info("出现错误:");
            logger.info(reply.cause());
            logger.info("资源变更，找不到资源编号为【"+auxiliaryId+"】");

            return;
        }
        });

    }

//    public void update(
//            String auxiliaryId,
//            String auxiliaryName,
//            Boolean isAdd,
//            Integer useAmount,
//            Handler<AsyncResult<Auxiliary>> asyncResultHandler){
//        Future<Auxiliary> future =Future.future();
//        if (StrUtil.isNullOrUndefined(auxiliaryId)){
//            future.fail("资源编号不能为空");
//            return;
//        }
//        if (StrUtil.isBlankOrUndefined(""+useAmount)){
//            future.fail("资源使用数量不能为空");
//            return;
//        }
//        this.pg.getById("auxiliary",auxiliaryId, Auxiliary.class, reply->{
//            if (reply.succeeded()){
//                Auxiliary auxiliary = reply.result();
//                Integer amount = auxiliary.getAmount();
//                Integer remainder = auxiliary.getRemainder();
//                if (isAdd){
//                    Integer result = useAmount + remainder;
//                    if (result > amount){
//
//                        auxiliary.setRemainder(amount);
//
//                    }else if(result <= amount){
//                        auxiliary.setRemainder(result);
//                    }
//                }else{
//                    Integer result = remainder - useAmount;
//                    if (result < 0){
//                        logger.info("资源变更，资源编号为【"+auxiliaryId+"】的数量不足");
//                        future.fail("资源名称为【"+auxiliaryName+"】的数量不足，请更换或者更新资源数量再保存");
//                        return;
//                    }else if(result >= 0){
//                        auxiliary.setRemainder(result);
//                    }
//                }
//                this.pg.update("auxiliary",auxiliary,auxiliaryId,replyUpdate->{
//
//                    if (replyUpdate.succeeded()){
//                        if (replyUpdate.result().getUpdated() == 0){
//                            future.fail("资源名称为【"+auxiliaryName+"】更新失败，请更换或者更新资源数量再保存");
//                            return;
//                        }
//                        future.tryComplete(auxiliary);
//                    }else{
//                        logger.info("资源变更，资源编号为【"+auxiliaryId+"】更新失败");
//                        future.fail("资源名称为【"+auxiliaryName+"】更新失败，请更换或者更新资源数量再保存");
//                        return;
//                    }
//                });
//            }else{
//                logger.info("资源变更，找不到资源编号为【"+auxiliaryId+"】");
//                future.fail("操作失败，找不到名称为【"+auxiliaryName+"】");
//                return;
//            }
//        });
//
//        future.setHandler(re->{
//            if (re.succeeded()){
//                asyncResultHandler.handle(Future.succeededFuture(re.result()));
//            }else{
//                asyncResultHandler.handle(Future.failedFuture(re.cause().getMessage()));
//            }
//        });
//    }


}
